//
//  ScanQRCodeVC.swift
//  卡鹿
//
//  Created by 时空矩人 on 16/3/19.
//  Copyright © 2016年 时空矩人. All rights reserved.
//

import UIKit

class ScanQRCodeVC: UIViewController {

    @IBOutlet weak var backgroundView: UIView!
    @IBOutlet weak var cornerImgView: UIImageView!
    
    @IBOutlet weak var showImgView: UIImageView!
    @IBOutlet weak var bottomLength: NSLayoutConstraint!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        //初始化设置
        setInit()
        
//        NSThread.sleepForTimeInterval(2)
        lol()

    }
    
    override func viewDidAppear(animated: Bool) {
        // 开始动画
        beginAnimation()
    }
    
    func lol() {
        
        // 开始动画(如果在这里
//        beginAnimation()
        
        // 开始扫描
        QRCodeTool.shareInstance.startScanQRCode(view) { (resultStr: [String]) -> () in
            print(resultStr)
            
            let lastStr: String! = resultStr.first
            
            //url  (http:// friend,pay)
            if lastStr.containsString("http://")
            {
                let url = NSURL(string: lastStr)
                UIApplication.sharedApplication().openURL(url!)
            }
        }
        
        // 设置扫描区域
        QRCodeTool.shareInstance.setInterstRect(backgroundView.frame)
        
        // 设置是否描绘边框
        QRCodeTool.shareInstance.isDrawFlag = true
    }
}

extension ScanQRCodeVC {
    func setInit() {
        
        var image = UIImage(named: "qrcode_border")
        let width = NSInteger(image!.size.width * 0.5)
        let heigh = NSInteger(image!.size.height * 0.5)
        image = image?.stretchableImageWithLeftCapWidth(width, topCapHeight: heigh)
        cornerImgView.image = image
    }
    
    // 开始动画
    func beginAnimation()
    {
        showImgView.hidden = false
        bottomLength.constant = backgroundView.frame.size.height
        view.layoutIfNeeded()
        
        bottomLength.constant = -backgroundView.frame.size.height
        UIView.animateWithDuration(1.3) { () -> Void in
            UIView.setAnimationRepeatCount(MAXFLOAT)
            self.view.layoutIfNeeded()
        }
//        view.layer.
        
    }
}
